<template>
  <div class="container">
    <van-image
        width="15rem"
        height="10rem"
        fit="contain"
        src="https://javawebprogram.oss-cn-beijing.aliyuncs.com/0bccf4e6-d60d-4dae-b89c-6847c0a04935.jpg"
    />
  </div>
  <div>
    <van-form @submit="onSubmit">
      <div>
        <van-cell-group inset>
          <van-field
              style="margin: 5px 0"
              v-model="initData.name"
              name="name"
              label="队伍名称"
              placeholder="请输入队伍名称"
              :rules="[{ required: true, message: '请输入队伍名称' }]"
          />
          <van-field
              style="margin: 5px 0"
              v-model="initData.description"
              rows="2"
              autosize
              label="队伍描述"
              type="textarea"
              maxlength="512"
              placeholder="请输入队伍描述"
              show-word-limit
          />
          <van-field
              style="margin: 5px 0"
              v-model="displayExpireTime"
              is-link
              readonly
              name="expireTime"
              label="过期时间"
              placeholder="点击选择过期时间"
              @click="showPicker = true"
          />
          <van-popup v-model:show="showPicker" position="bottom">
            <van-date-picker @confirm="onConfirm" @cancel="showPicker = false"/>
          </van-popup>
          <van-field name="status" label="队伍状态" style="margin: 5px 0">
            <template #input>
              <van-radio-group v-model="initData.status" direction="horizontal">
                <van-radio name="0">公开</van-radio>
                <van-radio name="1">私密</van-radio>
                <van-radio name="2">加密</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
              v-if="initData.status === '2'"
              style="margin: 5px 0"
              v-model="initData.password"
              name="password"
              type="password"
              label="密码"
              placeholder="请输入队伍密码"
              :rules="[{ required: true, message: '请输入队伍密码' }]"
          />
        </van-cell-group>
      </div>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          更新信息
        </van-button>
      </div>
    </van-form>
    {{ initData }}
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue';
import {showFailToast, showSuccessToast, showToast} from "vant";
import {useRouter, useRoute} from "vue-router";
import {getTeamById, getTeamList, updateTeam} from "../../api/Team.ts";

const router = useRouter();
const route = useRoute();

// 默认数据
const initData = ref({});

// 用户输入的响应式数据
const showPicker = ref(false);
const displayExpireTime = ref('')

// 点击确认日期触发的函数
const onConfirm = ({selectedValues}) => {
  initData.value.expireTime = selectedValues.join('-') + "T00:00:00Z";
  displayExpireTime.value = selectedValues.join('-');
  showPicker.value = false;
};

// 获取传递的队伍id
const teamId = route.query.id;

// 页面挂载时获取当前队伍信息
onMounted(async () => {
      if (teamId <= 0) {
        showFailToast("队伍不存在，请重新查询");
        return;
      }
      const result = await getTeamById(Number(teamId));
      if (result?.code === 0 && result?.data) {
        const teamData = result.data;
        // 关键：将 status 转换为字符串，与 van-radio 的 name 类型匹配
        initData.value = {
          ...teamData,
          status: String(teamData.status) // 确保是字符串类型
        };
        // 处理过期时间显示（假设后端返回格式为 "YYYY-MM-DDTHH:MM:SSZ"）
        if (teamData.expireTime) {
          displayExpireTime.value = teamData.expireTime.split('T')[0];
        } // 提取 "YYYY-MM-DD"
      } else {
        showFailToast("获取队伍信息失败");
      }
    }
)

/**
 * 点击创建队伍时触发的函数
 * @param values
 * @returns {Promise<void>}
 */
const onSubmit = async (values) => {
  // 格式化队伍状态信息
  const postData = ref({
    ...initData.value,
    status: Number(initData.value.status),
    // maxNum: '',
  });
  console.log(postData.value)
  // TODO 前端参数校验
  const result = await updateTeam(postData.value);
  if (result?.code === 0 && result?.data) {
    showSuccessToast('更新成功');
    await router.push({
      path: '/team',
      replace: true,
    });
  } else {
    // @ts-ignore
    showFailToast('更新失败' + (result.description ? `${result.description}` : ''));
  }
};


</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 10px 0 10px 0;
}
</style>